package com.proactive.webapp.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.CourseCategory1DAO;
import com.proactive.webapp.dao.CourseCategory2DAO;
import com.proactive.webapp.dao.CourseDAO;
import com.proactive.webapp.dao.CourseTagDAO;
import com.proactive.webapp.dao.MemberDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.entity.Course;
import com.proactive.webapp.entity.CourseCategory1;
import com.proactive.webapp.entity.CourseCategory2;
import com.proactive.webapp.entity.CourseTag;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.util.AwsUtil;
import com.proactive.webapp.util.CompressImage;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class MemberCourseController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	
	@RequestMapping(value = "/addCourseCont", method = RequestMethod.GET)
	public ModelAndView addCourseCont(HttpSession session) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			model.setViewName("addCourse");
			List<CourseCategory1> category1List = new ArrayList<CourseCategory1>();
			List<CourseCategory2> category2List = new ArrayList<CourseCategory2>();
			List<CourseTag> tagList = new ArrayList<CourseTag>();
			CourseCategory1DAO courseCategory1DAO = (CourseCategory1DAO) context.getBean("courseCategory1DAO");
			CourseCategory2DAO courseCategory2DAO = (CourseCategory2DAO) context.getBean("courseCategory2DAO");
			CourseTagDAO courseTagDAO = (CourseTagDAO) context.getBean("courseTagDAO");
			category1List = courseCategory1DAO.getList();
			category2List = courseCategory2DAO.getList(category1List.get(0).getId());
			tagList = courseTagDAO.getTop(10, category2List.get(0).getId());
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
			model.addObject("menuList", menuList);
			model.addObject("category1", category1List);
			model.addObject("category2", category2List);
			model.addObject("tag", tagList);
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	
	@RequestMapping(value = "/addCourse", method = RequestMethod.POST)
	public ModelAndView addCourse(@ModelAttribute Course course, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			String path1 = session.getServletContext().getRealPath("resources/image/course");
			String path2 = session.getServletContext().getRealPath("resources/file/course");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			course.setAccount(loginMember.getAccount());
			
			//new AWS
			AwsUtil awsUtil = new AwsUtil();
	        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
	        awsUtil.getInstance();

			//upload image
			if(course.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(course.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
				
	        	//rename and move
				File targetFile = new File(path1, newFileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	course.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
				
		        //compress image
				if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
		        }
				
				//upload file AWS
				try {		        	
					awsUtil.uploadFile("resources/image/course/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();		        
				course.setImagePath("resources/image/course/"+newFileName);
				
			}

			//upload file
			if(course.getFile().getSize() > 0){
				FileUtil fileUtil = new FileUtil(course.getFile().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();

	        	//rename and move
				File targetFile = new File(path2, newFileName);
				course.setFileName(fileUtil.getLowerCaseName());
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	course.getFile().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
				
	        	//upload file AWS
				try {
					awsUtil.uploadFile("resources/file/course/", targetFile);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //delete local file
		        targetFile.delete();
				course.setFilePath("resources/file/course/"+newFileName);
			}
			else{
				course.setFilePath("");
				course.setFileName("");
			}
			CourseDAO courseDAO = (CourseDAO)context.getBean("courseDAO");
			int courseID = courseDAO.insert(course);
			CourseTagDAO courseTagDAO = (CourseTagDAO) context.getBean("courseTagDAO");	
			String[] tags = course.getTags().split(",");
			for(String tagName : tags){
				if(!tagName.equals("")){
					CourseTag courseTag = new CourseTag();
					courseTag.setCid(courseID);
					courseTag.setTag(tagName);
					courseTagDAO.insert(courseTag);
				}
			}

			model.setViewName("redirect:/showCourse?id="+courseID);
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	
	@RequestMapping(value = "/memberCourse", method = RequestMethod.GET)
	public ModelAndView getMemberCourseList(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView();
		Member loginMember = (Member)session.getAttribute("loginMember");
		if (request.getParameter("id") != null) {
			MemberDAO memberDAO = (MemberDAO) context.getBean("memberDAO");
			CourseDAO courseDAO = (CourseDAO) context.getBean("courseDAO");
			Member member = new Member();			
			List<Course> courseList = new ArrayList<Course>();
			
			String memberNO = request.getParameter("id");
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			
			member.setMemberNO(memberNO);
			member = memberDAO.getByMemberNO(member);//用memberNO取得memberAccount
			if(member.getAccount()!=null){
				if(loginMember != null)
					member = memberDAO.getByLogin(member, loginMember.getAccount());//取得member資料
				int count = 0;
				if(member.isMyselfFlag())
					count = courseDAO.countTotalByWriter(member.getAccount());
				else
					count = courseDAO.countTotalByMember(member.getAccount());
				
				//set pager
				int pageSize = 9;
				String pageUrl = "memberCourse";
				String pageEndUrl1 = "&id="+memberNO;
				PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
				pageCount.calculate();
				
				if(member.isMyselfFlag())
					courseList = courseDAO.getListByWriter(member.getAccount(), pageCount.getStart(), pageSize);
				else
					courseList = courseDAO.getListByMember(member.getAccount(), pageCount.getStart(), pageSize);
				
				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				
				//set model
				model.addObject("page", pageCount);
				model.addObject("member", member);
				model.addObject("courseList", courseList);
				model.addObject("menuList", menuList);
				model.setViewName(loginMember!=null?"memberCourse1":"memberCourse2");
				
			}
			else
				model.setViewName("redirect:/");
			
		} 
		else
			model.setViewName(loginMember!=null?"redirect:/memberCourse?id="+loginMember.getMemberNO():"redirect:/login");

		
		return model;
	}
	
	@RequestMapping(value = "/actCourse", method = RequestMethod.POST)
	public ModelAndView actCourse(int id, String act, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){//檢查登入
			CourseDAO courseDAO = (CourseDAO) context.getBean("courseDAO");
			Course course = new Course();
			course.setId(id);
			course = courseDAO.getByWriter(course);
			if(course.getAccount().equals(loginMember.getAccount())){//檢查是否為作者
				
				if(act.equals("delete")){//delete course
					//new AWS
					AwsUtil awsUtil = new AwsUtil();
			        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
			        awsUtil.getInstance();			        
			        //delete image
					if(!course.getImagePath().equals("")){
						awsUtil.deleteFile(course.getImagePath());
					}
					//delete file
					if(!course.getFilePath().equals("")){
						awsUtil.deleteFile(course.getFilePath());
					}
					course.setStatus(3);					
				}
				else if(act.equals("show")){//show course
					course.setStatus(1);
				}
				else if(act.equals("hide")){//hide course
					course.setStatus(2);
				}
				courseDAO.updateStatus(course);
				model.setViewName("redirect:"+request.getHeader("referer"));
			}
			else 
				model.setViewName("redirect:/memberCourse");
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
	@RequestMapping(value = "/modiCourseCont", method = RequestMethod.GET)
	public ModelAndView modiCourseCont(HttpSession session, int id) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			CourseDAO courseDAO = (CourseDAO) context.getBean("courseDAO");
			Course course = new Course();
			course.setId(id);
			course = courseDAO.getByWriter(course);
			if(course.getAccount().equals(loginMember.getAccount())){
				model.setViewName("modiCourse");
				List<CourseCategory1> category1List = new ArrayList<CourseCategory1>();
				List<CourseCategory2> category2List = new ArrayList<CourseCategory2>();
				List<CourseTag> tagList = new ArrayList<CourseTag>();
				List<CourseTag> tags = new ArrayList<CourseTag>();
				String tagString = "";
				CourseCategory1DAO courseCategory1DAO = (CourseCategory1DAO) context.getBean("courseCategory1DAO");
				CourseCategory2DAO courseCategory2DAO = (CourseCategory2DAO) context.getBean("courseCategory2DAO");
				CourseTagDAO courseTagDAO = (CourseTagDAO) context.getBean("courseTagDAO");
				category1List = courseCategory1DAO.getList();
				category2List = courseCategory2DAO.getList(course.getCategory1ID());
				tagList = courseTagDAO.getTop(10, course.getCategory2ID());
				tags = courseTagDAO.getListByCourseID(id);
				for (int i=0; i<tags.size(); i++) {
					CourseTag tag = tags.get(i);
					tagString += tag.getTag();
					if(i < tags.size())
						tagString += ",";
				}
				for(int j=0; j<category1List.size(); j++){
					if(category1List.get(j).getId() == course.getCategory1ID())
						category1List.get(j).setClassString("selected");
				}
				for(int k=0; k<category2List.size(); k++){
					if(category2List.get(k).getId() == course.getCategory2ID())
						category2List.get(k).setClassString("selected");
				}
				
				course.setTags(tagString);

				List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 0);
				model.addObject("menuList", menuList);
				model.addObject("category1", category1List);
				model.addObject("category2", category2List);
				model.addObject("tag", tagList);
				model.addObject("course", course);
			}
			else
				model.setViewName("redirect:/course");
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
	}
	
	@RequestMapping(value = "/modiCourse", method = RequestMethod.POST)
	public ModelAndView modiCourse(@ModelAttribute Course course, HttpSession session, HttpServletRequest request) {
		Member loginMember = (Member)session.getAttribute("loginMember");
		ModelAndView model = new ModelAndView();
		if(loginMember != null){
			CourseDAO courseDAO = (CourseDAO)context.getBean("courseDAO");
			Course oldCourse = new Course();
			oldCourse.setId(course.getId());
			oldCourse = courseDAO.getByWriter(oldCourse);
			if(oldCourse.getAccount().equals(loginMember.getAccount())){
				//new AWS
				AwsUtil awsUtil = new AwsUtil();
		        awsUtil.setPropertyPath(request.getServletContext().getRealPath("../AwsCredentials.properties"));
		        awsUtil.getInstance();
		        
				String path = session.getServletContext().getRealPath("/");
				String path1 = session.getServletContext().getRealPath("resources/image/course");
				String path2 = session.getServletContext().getRealPath("resources/file/course");
				DateConversion dateConversion = new DateConversion();
				Date now = new Date();
				course.setAccount(loginMember.getAccount());
				
				//upload image
				if(course.getImage().getSize() > 0){
					FileUtil fileUtil = new FileUtil(course.getImage().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path1, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	course.getImage().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
			        //delete original file
			        if(!oldCourse.getImagePath().equals("")){
			        	awsUtil.deleteFile(oldCourse.getImagePath());
			        }
			        
			        //compress image
					if(!fileUtil.getFileType().equals("gif")){
			    		CompressImage compressImage = new CompressImage();
			        	compressImage.compress(path1+"/", newFileName, 0, 0, false);
			        }
					
					//upload file AWS
			        try {
						awsUtil.uploadFile("resources/image/course/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();					
		        	course.setImagePath("resources/image/course/"+newFileName);
					
				}
				else
		        	course.setImagePath(oldCourse.getImagePath());
				
				//upload file
				if(course.getFile().getSize() > 0){
					FileUtil fileUtil = new FileUtil(course.getFile().getOriginalFilename());
					String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ loginMember.getMemberNO() + "." + fileUtil.getFileType();
					
					//rename and move
					File targetFile = new File(path2, newFileName);
			        if(!targetFile.exists()){
			            targetFile.mkdirs();
			        }
			        try {
			        	course.getFile().transferTo(targetFile);
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			        
			        //delete original file
			        if(!oldCourse.getFilePath().equals("")){
			        	awsUtil.deleteFile(oldCourse.getFilePath());
			        }
			        
			     	//upload file AWS
			        try {
						awsUtil.uploadFile("resources/file/course/", targetFile);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			        
			        //delete local file
			        targetFile.delete();
			        
		        	course.setFilePath("resources/file/course/"+newFileName);
		        	course.setFileName(fileUtil.getLowerCaseName());
				}
				else{
		        	course.setFilePath(oldCourse.getFilePath());
		        	course.setFileName(oldCourse.getFileName());
		        }
				
				if(!course.getFileUrl().equals("")){

		        	course.setFilePath("");
		        	course.setFileName("");
					if(!oldCourse.getFilePath().equals("")){
						awsUtil.deleteFile(oldCourse.getFilePath());
			        }
				}
				else
					course.setIsFile(1);
				courseDAO.update(course);
				
				
				
				CourseTagDAO courseTagDAO = (CourseTagDAO) context.getBean("courseTagDAO");	
				courseTagDAO.delete(course.getId());
				String[] tags = course.getTags().split(",");
				for(String tagName : tags){
					if(!tagName.equals("")){
						CourseTag courseTag = new CourseTag();
						courseTag.setCid(course.getId());
						courseTag.setTag(tagName);
						courseTagDAO.insert(courseTag);
					}
				}
				
			}
			model.setViewName("redirect:/memberCourse?id="+loginMember.getMemberNO());
			
		}
		else
			model.setViewName("redirect:/login");
		return model;
 
	}	
	
}
